<?php

namespace admin\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;

use yii\data\Pagination;
use yii\data\ArrayDataProvider;

use PHPExcel_Style_Alignment;
use PHPExcel_Style_Border;
use PHPExcel_Style_Fill;
use PHPExcel_IOFactory;
use app\models\UploadForm;
use common\models\TaskType;
use common\models\Task;
use common\lib\Helper;

class TaskController extends Controller
{
    public $enableCsrfValidation = false;
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    '*'   => ['get'],
                    'create' => ['get','post'],
                    'close'  => ['get','post'],
                ],
            ],
        ];
    }

    /**
     * 任务列表
     *
     * @return string
     */
    public function actionTaskList()
    {
//        if(!Yii::$app->user->can('task.list')){
//            return $this->render('/site/403');
//        }
        $get = Yii::$app->request->get();
        $params = array(
            'title'      => isset( $get['title'] ) ? $get['title'] : '',
            'page'       => isset( $get['page'] ) ? intval( $get['page'] ) : 1,
            'type'       => isset( $get['type'] ) ? intval( $get['type'] ) : 0,
            'daily_type' => isset( $get['daily_type'] ) ? intval( $get['daily_type'] ) : 1,
            'start'      => isset( $get['start'] ) ? trim($get['start']) : '',
            'end'        => isset( $get['end'] ) ? trim($get['end']) : '', 
        );
        $data = \common\models\Task::getTaskList( $params );
        $data['select'] = $params;
        return $this->render('task-list',$data);
    }
    
    /**
     * 开启任务
     */
    public function actionOpen()
    {
//        if(!Yii::$app->user->can('task.open')){
//            return $this->render('/site/403');
//        }
        $get = Yii::$app->request->get();
        $id = $get['id'];
        $task = Task::findOne( $id );
        $task->put_in_status = 1;
        $task->start_time = date('Y-m-d H:i:s');
        if( $task->save() ){
            \Yii::$app->getSession()->setFlash('success', '操作成功');
        }else{
             \Yii::$app->getSession()->setFlash('error', '操作失败');
        }
        return $this->redirect('/task/task-list');
    }
    
    /**
     * 关闭任务
     */
    public function actionClose()
    {
//        if(!Yii::$app->user->can('task.close')){
//            return $this->render('/site/403');
//        }
        $now = date('Y-m-d H:i:s');
        if(Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $id = $post['id'];
            $res = Task::updateAll(['put_in_status'=>0,'end_time'=>$now],'id in ('.implode(',',$id).') and put_in_status=1');
            if($res){
                echo json_encode(['status'=>0,'msg'=>'修改成功']);
                exit;
            }else{
                echo json_encode(['status'=>1,'msg'=>'修改失败']);
                exit;
            }
        }
        $get = Yii::$app->request->get();
        $id = $get['id'];    
        $task = Task::findOne( $id );
        $task->put_in_status = 0;
        $task->end_time = $now;
        $res = $task->save();
        if( $res ){
            \Yii::$app->getSession()->setFlash('success', '操作成功');
        }else{
             \Yii::$app->getSession()->setFlash('error', '操作失败');
        }
        return $this->redirect('/task/task-list');
    }
    
    /**
     * 删除任务
     */
    public function actionDelete()
    {
//        if(!Yii::$app->user->can('task.delete')){
//            return $this->render('/site/403');
//        }
        $get = Yii::$app->request->get();
        $id = $get['id'];
        $task = Task::findOne( $id );
        $task->status = 0;
        if( $task->save() ){
            \Yii::$app->getSession()->setFlash('success', '操作成功');
        }else{
             \Yii::$app->getSession()->setFlash('error', '操作失败');
        }
        return $this->redirect('/task/task-list');
    }

    /**
     * 下载筛选结果
     */
    public function actionDownLoad()
    {
        if(!Yii::$app->user->can('data.down-load')){
            return $this->render('/site/403');
        }
        $get = Yii::$app->request->get();
        $username = Yii::$app->user->identity->username;
        if($username == 'songhao_test' || $username == 'test1'){
            $username = 'admin';
        }
//        $username = 'szxz';
        $channel = $get['channel'];
        $start = $get['start'];
        $end = $get['end'];
        $data = ChannelNowData::getDatas($username,$channel,'all',$start,$end,1);
        $excel = new \PHPExcel();
        $excel->setActiveSheetIndex(0);
        //报表头的输出
        $excel->getActiveSheet()->mergeCells('A1:E1');
        $excel->getActiveSheet()->setCellValue('A1',$username.'渠道数据');

        //表格头的输出
        $excel->setActiveSheetIndex(0)->setCellValue('A2','时间');
        $excel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
        $excel->setActiveSheetIndex(0)->setCellValue('B2','渠道名');
        $excel->getActiveSheet()->getColumnDimension('B')->setWidth(17);
        $excel->setActiveSheetIndex(0)->setCellValue('C2','新增');
        $excel->getActiveSheet()->getColumnDimension('C')->setWidth(22);
        $excel->setActiveSheetIndex(0)->setCellValue('D2','活跃');
        $excel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
        if(Yii::$app->user->can('data.profit')){
            $excel->setActiveSheetIndex(0)->setCellValue('E2','收入');
            $excel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
        }
        if(Yii::$app->user->can('data.mission')){
            $excel->setActiveSheetIndex(0)->setCellValue('F2','完成数');
            $excel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        }

        if(Yii::$app->user->can('data.profit')){
            //设置居中
            $excel->getActiveSheet()->getStyle('A2:E2')
                ->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            //设置边框
            $excel->getActiveSheet()->getStyle('A2:E2' )
                ->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->getActiveSheet()->getStyle('A2:E2' )
                ->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->getActiveSheet()->getStyle('A2:E2' )
                ->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->getActiveSheet()->getStyle('A2:E2' )
                ->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->getActiveSheet()->getStyle('A2:E2' )
                ->getBorders()->getVertical()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);

            //设置颜色
            $excel->getActiveSheet()->getStyle('A2:E2')->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF66CCCC');
        }

        if(Yii::$app->user->can('data.mission')){
            //设置居中
            $excel->getActiveSheet()->getStyle('A2:F2')
                ->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            //设置边框
            $excel->getActiveSheet()->getStyle('A2:F2' )
                ->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->getActiveSheet()->getStyle('A2:F2' )
                ->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->getActiveSheet()->getStyle('A2:F2' )
                ->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->getActiveSheet()->getStyle('A2:F2' )
                ->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->getActiveSheet()->getStyle('A2:F2' )
                ->getBorders()->getVertical()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);

            //设置颜色
            $excel->getActiveSheet()->getStyle('A2:F2')->getFill()
            ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF66CCCC');
        }
        $n = 0;
        foreach ( $data['list'] as $product )
        {
            if ( $product )
            {
                //明细的输出
                $excel->getActiveSheet()->setCellValue('A'.($n+3) ,$product['date']);
                $excel->getActiveSheet()->setCellValue('B'.($n+3) ,$product['channel']);
                $excel->getActiveSheet()->setCellValue('C'.($n+3) ,$product['new']);
                $excel->getActiveSheet()->setCellValue('D'.($n+3) ,$product['old']);
                if(Yii::$app->user->can('data.profit')){
                    $excel->getActiveSheet()->setCellValue('E'.($n+3) ,$product['expect']);
                }
                if(Yii::$app->user->can('data.mission')){
                    $excel->getActiveSheet()->setCellValue('F'.($n+3) ,$product['channel_mission']);
                }
//                //设置边框
//                $currentRowNum = $n+3;
//                $excel->getActiveSheet()->getStyle('A'.($n+3).':E'.$currentRowNum )
//                        ->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
//                $excel->getActiveSheet()->getStyle('A'.($n+3).':E'.$currentRowNum )
//                        ->getBorders()->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
//                $excel->getActiveSheet()->getStyle('A'.($n+3).':E'.$currentRowNum )
//                        ->getBorders()->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
//                $excel->getActiveSheet()->getStyle('A'.($n+3).':E'.$currentRowNum )
//                        ->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
//                $excel->getActiveSheet()->getStyle('A'.($n+3).':E'.$currentRowNum )
//                        ->getBorders()->getVertical()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
//                $excel->getActiveSheet()->getStyle('A'.($n+3).':E'.$currentRowNum )
//                        ->getBorders()->getVertical()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                $n = $n +1;
            }
        }
    
        //设置分页显示
        //$excel->getActiveSheet()->setBreak( 'I55' , PHPExcel_Worksheet::BREAK_ROW );
        //$excel->getActiveSheet()->setBreak( 'I10' , PHPExcel_Worksheet::BREAK_COLUMN );
        $excel->getActiveSheet()->getPageSetup()->setHorizontalCentered(true);
        $excel->getActiveSheet()->getPageSetup()->setVerticalCentered(false);
    
    
        ob_end_clean();
        ob_start();
    
        header('Content-Type : application/vnd.ms-excel');
        header('Content-Disposition:attachment;filename="'."{$username}渠道数据表-".date("Y年m月j日").'.xls"');
        $objWriter= PHPExcel_IOFactory::createWriter($excel,'Excel5');
        $objWriter->save('php://output');
    }
    
    public function actionCreate(){
        
//        $type = new TaskType();
//        $typeArr = $type->getTypeLists();
        $typeArr = TaskType::getAllTaskType();
        $id = Yii::$app->request->get('id');
        $data = [];
        if( $id ){
            $data = Task::getById(trim($id)); 
        }
        if(Yii::$app->request->isPost){
            $task = new Task();
            $res = $task->createTask();
            if($res){
//                return Helper::xd_api_json('ERROR_SUCCESS');
                echo json_encode(['status' => 0]);
                exit;
            }else{
//                return Helper::xd_api_json('ERROR_INSERT_ERROR');
                echo json_encode(['status' => 11,'msg' => '操作失败']);
                exit;
            }
        }
        return $this->render('create',['typeArr' => $typeArr,'data' => $data]);
    }
}
